package com.concurrent.data.thread.utils;


import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 哲思小辉
 * @version 1.0.0
 * @ClassName GsonJsonUtil.java
 * @Description Gson格式化工具
 * @Param
 * @createTime 2020年05月13日 16:40:00
 */
@Slf4j
public class GsonJsonUtil {
    private GsonJsonUtil() {
    }

    private static final Gson gson = new GsonBuilder()
            .enableComplexMapKeySerialization() //当Map的key为复杂对象时,需要开启该方法
            .serializeNulls() //当字段值为空或null时，依然对该字段进行转换
            .setDateFormat("yyyy-MM-dd HH:mm:ss:SSS") //时间转化为特定格式
            .disableHtmlEscaping() //防止特殊字符出现乱码
            .registerTypeAdapter(Double.class, (JsonSerializer<Double>) (src, typeOfSrc, context) -> {
                if (src == src.longValue()) {
                    return new JsonPrimitive(src.longValue());
                }
                return new JsonPrimitive(src);
            }).create();


    /**
     * 转成json 字符串 如果是字符串就直接返回原字符串
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        String jsonStr = null;
        try {
            if (object instanceof String) {
                return (String) object;
            }
            jsonStr = gson.toJson(object);
        } catch (Exception e) {
            log.error("json数据格式化报异常{}", e);
        }
        return jsonStr;
    }


    /**
     * 转成Map<String,T>
     *
     * @param object
     * @return
     */
    public static <T> Map<String, T> toMap(Object object, Class<T> clzz) {
        String text = toJson(object);
        Map<String, T> map = null;
        if (text != null) {
            try {
                map = gson.fromJson(text, new ParameterizedTypeMap(clzz));
            } catch (Exception e) {
                log.error("json字符串转Map<String, T>异常：{}", e);
            }
        }
        return map;
    }

    /**
     * 转成Map<String,JsonObject>
     *
     * @param object
     * @return
     */
    public static Map<String, JsonObject> toMap(Object object) {
        String text = toJson(object);
        Map<String, JsonObject> map = null;
        if (text != null) {
            try {
                map = gson.fromJson(text, new TypeToken<Map<String, JsonObject>>() {
                }.getType());
            } catch (Exception e) {
                log.error("json字符串转Map<String, JsonObject>异常：{}", e);
            }
        }
        return map;
    }

    /**
     * 转成List 里面默认数据类型是LinkedTreeMap所以直接转成JsonObject类型
     *
     * @param object
     * @return
     */
    public static List<JsonObject> toList(Object object) {
        String text = toJson(object);
        List<JsonObject> list = null;
        if (text != null) {
            try {
                list = gson.fromJson(text, new TypeToken<List<JsonObject>>() {
                }.getType());
            } catch (Exception e) {
                log.error("json字符串转List<JsonObject>异常：{}", e);
            }
        }
        return list;
    }

    /**
     * 转成List<T>
     *
     * @param object
     * @param clzz
     * @param <T>
     * @return
     */
    public static <T> List<T> toList(Object object, Class<T> clzz) {
        String text = toJson(object);
        List<T> list = null;
        if (text != null) {
            try {
                list = gson.fromJson(text, new ParameterizedTypeList(clzz));
            } catch (Exception e) {
                log.error("json字符串转List<T>异常：{}", e);
            }
        }
        return list;
    }

    /**
     * 转成JavaBean
     *
     * @param object
     * @param clzz
     * @param <T>
     * @return
     */
    public static <T> T toJavaBean(Object object, Class<T> clzz) {
        String text = toJson(object);
        T t = null;
        if (text != null && clzz != null) {
            try {
                t = gson.fromJson(text, clzz);
            } catch (Exception e) {
                log.error("json字符串转T异常：{}", e);
            }
        }
        return t;
    }

    /**
     * 转成Set<JsonObject>
     *
     * @param object
     * @return
     */
    public static Set<JsonObject> toSet(Object object) {
        String text = toJson(object);
        Set<JsonObject> set = null;
        if (text != null) {
            try {
                set = gson.fromJson(text, new TypeToken<Set<JsonObject>>() {
                }.getType());
            } catch (Exception e) {
                log.error("json字符串转Set<JsonObject>异常：{}", e);
            }
        }
        return set;
    }

    /**
     * 转成Set<T>
     *
     * @param object
     * @param clzz
     * @return
     */
    public static <T> Set<T> toSet(Object object, Class<T> clzz) {
        String text = toJson(object);
        Set<T> set = null;
        if (text != null) {
            try {
                set = gson.fromJson(text, new ParameterizedTypeSet(clzz));
            } catch (Exception e) {
                log.error("json字符串转Set<T>异常：{}", e);
            }
        }
        return set;
    }


    private static class ParameterizedTypeList implements ParameterizedType {
        Class clazz;

        public ParameterizedTypeList(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }

    private static class ParameterizedTypeSet implements ParameterizedType {
        Class clazz;

        public ParameterizedTypeSet(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @Override
        public Type getRawType() {
            return Set.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }


    private static class ParameterizedTypeMap implements ParameterizedType {
        Class clazz;

        public ParameterizedTypeMap(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{String.class, clazz};
        }

        @Override
        public Type getRawType() {
            return Map.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }
}

